package com.main.tabletobean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import com.main.util.FileReadOrSave;

/**
 * 
 * @author Cobbage
 */
public class TableToBean {

	/**
	 * 获取连接
	 * @return
	 */
	public static Connection getConnection(){
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			String url = "jdbc:oracle:thin:@127.0.0.1:1521/orcl";
			String user = "webservice";
			String password = "webservice";
			Properties properties = new Properties();
			properties.put("user", user);
			properties.put("password", password);
			properties.put("remarksReporting","true");//想要获取数据库结构中的注释，这个值是重点
			return DriverManager.getConnection(url,properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 获取表结构
	 * @param tableName
	 * @return
	 */
	public static List<ColumnModel> getTableStructure(String tableName){
		List<ColumnModel> columnModelList = new ArrayList<ColumnModel>();
		try {
			//TODO 表相关
			//ResultSet tableSet = metaData.getTables(null, "%",tableName,new String[]{"TABLE"}); 
			//TODO 字段相关
			ResultSet columnSet = getConnection().getMetaData().getColumns(null,"%",tableName.toUpperCase(),"%");
			ColumnModel columnModel = null;
			while(columnSet.next()){
				columnModel = new ColumnModel();
				columnModel.setColumnName(columnSet.getString("COLUMN_NAME"));
				columnModel.setColumnSize(columnSet.getInt("COLUMN_SIZE"));
				columnModel.setDataType(columnSet.getString("DATA_TYPE"));
				columnModel.setRemarks(columnSet.getString("REMARKS"));
				columnModel.setTypeName(columnSet.getString("TYPE_NAME"));
				String columnClassName = ColumnTypeEnum.getColumnTypeEnumByDBType(columnModel.getTypeName());
				//String fieldName = getFieldName(columnModel.getColumnName());
				String fieldName =columnModel.getColumnName().substring(0,1).toLowerCase()+columnModel.getColumnName().toLowerCase().substring(1);
				String fieldType = Class.forName(columnClassName).getSimpleName();
				columnModel.setFieldName(fieldName);
				columnModel.setColumnClassName(columnClassName);
				columnModel.setFieldType(fieldType);
				columnModel.setIsPk(false);
    			columnModelList.add(columnModel);
    			//System.out.println(columnModel.toString());
			}
			
			//获取主键
			ResultSet pkSet=getConnection().getMetaData().getPrimaryKeys(null, null, tableName.toUpperCase());
			while(pkSet.next()){  
			    String primaryKeyColumnName = pkSet.getString("COLUMN_NAME"); 
			   for(ColumnModel cmd:columnModelList){
				   if(primaryKeyColumnName.equals(cmd.getColumnName())){
					   cmd.setIsPk(true);
					   //修改pk为string类型
					   cmd.setColumnClassName("java.lang.String");
					   cmd.setFieldType(Class.forName("java.lang.String").getSimpleName());
				   }
			   }
			}  
		} catch (Exception e) {
			e.printStackTrace();
		}
		return columnModelList;
	}

	/**
	 * 将数据库字段转换成bean属性
	 * @param columnName
	 * @return
	 */
	private static String getFieldName(String columnName) {
		char[]  columnCharArr = columnName.toLowerCase().toCharArray();
		StringBuffer sb = new StringBuffer();
		int ad = -1;
		for (int i = 0; i < columnCharArr.length; i++) {
			  char cur = columnCharArr[i];
			  if(cur=='_'){
				  ad = i;
			  }else{
				  if((ad+1)==i&&ad!=-1){
					  sb.append(Character.toUpperCase(cur));
				  }else{
					  sb.append(cur);
				  }
				  ad=-1;
			  }
		}
		return sb.toString();
	}
	
	
	/**
	 * 从表结构中去生成javabean
	 * @param structureList
	 * @param beanName
	 * @return
	 */
	public static String genJavaBeanFromTableStructure(List<ColumnModel> columnModelList,String pack,String beanName){
		StringBuffer sb = new StringBuffer();
		StringBuffer body = new StringBuffer();
		StringBuffer toString=new StringBuffer();
		Set<String> imp=new HashSet<String>();
		try {
			//处理类头
			sb.append("public class "+toFirstCharUpCase(beanName)+" {\r\n");
			
			//处理属性
			for (ColumnModel columnModel : columnModelList) {
				if(null!=columnModel.getRemarks()&&!"".equals(columnModel.getRemarks())){
					sb.append("	//"+columnModel.getRemarks()+" \r\n");
				}
				sb.append("	private "+columnModel.getFieldType()+" "+columnModel.getFieldName()+";\r\n");
				if(!"String".equals(columnModel.getFieldType())){
					imp.add(columnModel.getColumnClassName());
				}
			}
			sb.append("\r\n");
			
			//get set
			for (ColumnModel columnModel : columnModelList) {
				sb.append(
						"\tpublic "+columnModel.getFieldType()+" get"+toFirstCharUpCase((String) columnModel.getFieldName())+"() {\r\n" +
						"\t\treturn "+columnModel.getFieldName()+";\r\n" + 
						"\t}\r\n" + 
						"\r\n" + 
						"\tpublic void set"+toFirstCharUpCase((String) columnModel.getFieldName())+"("+columnModel.getFieldType()+" "+columnModel.getFieldName()+") {\r\n" + 
						"\t\tthis."+columnModel.getFieldName()+" = "+columnModel.getFieldName()+";\r\n" + 
						"\t}\r\n\r\n");
				
				//toString拼接
				toString.append(columnModel.getFieldName()+"=\"+"+columnModel.getFieldName()+"+\",");
			}
			
			//toStrin方法也添加上来
			sb.append("\t@Override\r\n\tpublic String toString() {\r\n");
			sb.append("\treturn \""+toFirstCharUpCase(beanName)+"[");
			String str=toString.toString();
			if(!"".equals(str)){
				sb.append(str.substring(0,str.length()-2));
			}
			sb.append("\"]\";\r\n\t}\r\n");
			sb.append("}\r\n");
			
			//处理包
			if(null!=pack&&!"".equals(pack)){
				body.append("package "+pack+";\r\n\r\n");
			}
			
			//处理导入
			for(String s:imp){
				body.append("import "+s+";\r\n");
			}
			
			body.append(sb);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return body.toString();
	}
	
	/**
	 * 将首字母变大写
	 * @param str
	 * @return
	 */
	public static String toFirstCharUpCase(String str){
		char[]  columnCharArr = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < columnCharArr.length; i++) {
			  char cur = columnCharArr[i];
			  if(i==0){
				  sb.append(Character.toUpperCase(cur));
			  }else{
				  sb.append(cur);
			  }
		}
		return sb.toString();
	}

	/**
	 * @param pack
	 * @param className
	 * @param table
	 * @return
	 */
	public static String getClass(String pack,String className,String table){
		List<ColumnModel> columnModelList = TableToBean.getTableStructure(table);
		return genJavaBeanFromTableStructure(columnModelList,pack,className);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	 //System.out.println(TableToBean.class.getResource("/").toString().substring(6)+"config/");	
//		System.out.println(File.pathSeparator+" "+File.separator);
     String count=TableToBean.getClass("com.test.bean","QuartzTask","quartz_task");
     FileReadOrSave frs=new FileReadOrSave();
     frs.saveFileContent("D:/workspace_new/WebServicesPlatForm/src/com/test/bean", "QuartzTask.java", count, false);
	}
}
